// @ts-nocheck

import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Box,
  Button,
  Flex,
  ModalFooter,
  ModalBody,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  TableContainer,
  useTheme,
  Switch,
  Link,
  Input,
  MenuList,
  MenuItem,
  MenuButton,
  Menu,
  Stack,
  Spinner
} from '@chakra-ui/react';
import {
  createAOpenApiKey,
  putOpenApiKey
} from '@/web/support/openapi/api';
import { getOpenApiKeys, delOpenApiById, } from '@/web/support/openapi/weixin'
import type { EditApiKeyProps } from '@/global/support/api/openapiReq';
import { useQuery, useMutation } from '@tanstack/react-query';
import { useLoading } from '@/web/common/hooks/useLoading';
import dayjs from 'dayjs';
import { AddIcon, QuestionOutlineIcon } from '@chakra-ui/icons';
import { useCopyData } from '@/web/common/hooks/useCopyData';
import { feConfigs } from '@/web/common/system/staticData';
import { useTranslation } from 'react-i18next';
import MyIcon from '@/components/Icon';
import MyModal from '@/components/MyModal';
import { useForm } from 'react-hook-form';
import { useRequest } from '@/web/common/hooks/useRequest';
import MyTooltip from '@/components/MyTooltip';
import { setDate } from 'date-fns';
import axios from 'axios';
import { now } from 'lodash';

type EditProps = EditApiKeyProps & { _id?: string };
const defaultEditData: EditProps = {
  name: '',
  limit: {
    credit: -1
  }
};


const ApiKeyTable = ({ tips, appId }: { tips: string; appId?: string }) => {
  const [imgId, setImg] = useState('')
  //根据应用id获取镜像
  axios.get(`/apiss/getImageByAppId?appId=${appId}`).then(res => {
    // console.log(3332,res.data.data);
    if (imgId == ''&&res.data.data!=null) {
      setImg(res.data.data.imageId)
    }
    // const {
    //   data: apiKeys = [],
    //   isLoading: isGetting,
    //   refetch
    // } = useQuery(['getOpenApiKeys', imgId], () => getOpenApiKeys({ appId:imgId }));
    // useEffect(() => {
    //   setBaseUrl(`${location.origin}/api`);
    // }, []);

    if(res.data.data!=null){
      axios.get(`/apiss/getImageByAppId?imageId=${res.data.data.imageId}`).then(ress => {
        console.log(ress, 3321);
  
      })
    }
  
  })
  const { t } = useTranslation();
  const { Loading } = useLoading();
  const theme = useTheme();
  const { copyData } = useCopyData();
  const [baseUrl, setBaseUrl] = useState('https://fastgpt.run/api');
  const [editData, setEditData] = useState<EditProps>();
  const [apiKey, setApiKey] = useState('');


  const { mutate: onclickRemove, isLoading: isDeleting } = useMutation({
    mutationFn: async (id: string) => delOpenApiById(id),
    onSuccess() {
      refetch();
      stop(containId)
    }
  });
  const stop = (containId) => {
    // console.log(121121212);

    axios.get(`/apiss/deleteContainer?containId=${containId}`)
  }

  const {
    data: apiKeys = [],
    isLoading: isGetting,
    refetch
  } = useQuery(['getOpenApiKeys', imgId], () => getOpenApiKeys({ appId: imgId }));
  useEffect(() => {
    setBaseUrl(`${location.origin}/api`);
  }, []);

  return (
    <Flex flexDirection={'column'} h={'100%'} position={'relative'}>
      <Box display={['block', 'flex']} py={[0, 3]} px={5} alignItems={'center'}>
        <Box flex={1}>
          <Flex alignItems={'flex-end'}>
            <Box fontSize={['md', 'xl']} fontWeight={'bold'}>
              微信接入
            </Box>
            {/* <Link
              href={feConfigs.openAPIDocUrl || 'https://doc.fastgpt.run/docs/development/openapi'}
              target={'_blank'}
              ml={1}
              color={'myBlue.600'}
            >
              查看文档
            </Link> */}
          </Flex>
          {/* <Box fontSize={'sm'} color={'myGray.600'}>
            {tips}
          </Box> */}
        </Box>
        {/* <Flex
          mt={[2, 0]}
          bg={'myWhite.600'}
          py={2}
          px={4}
          borderRadius={'md'}
          cursor={'pointer'}
          userSelect={'none'}
          onClick={() => copyData(baseUrl, '已复制 API 地址')}
        >
          <Box border={theme.borders.md} px={2} borderRadius={'md'} fontSize={'sm'}>
            API根地址
          </Box>
          <Box ml={2} color={'myGray.900'} fontSize={['sm', 'md']}>
            {baseUrl}
          </Box>
        </Flex> */}
        <Box mt={[2, 0]} textAlign={'right'}>
          <Button
            background={'#008363'}
            ml={3}
            color={'white'}
            width={'96px'}
            height={'40px'}
            leftIcon={<AddIcon fontSize={'md'} />}
            // variant={'base'}
            onClick={() =>
              setEditData({
                ...defaultEditData,
                appId
              })
            }
          >
            新建
          </Button>
        </Box>
      </Box>
      <TableContainer mt={2} position={'relative'} minH={'300px'}>
        <Table>
          <Thead fontSize={'14px'}>
            <Tr>
              {/* <Th>{t('Name')}</Th> */}
              <Th>名称</Th>
              <Th>微信名</Th>
              <Th>状态</Th>

              {/* <Th>微信号</Th> */}

              <Th>创建时间</Th>
              <Th>最后一次使用时间</Th>
              <Th />
            </Tr>
          </Thead>
          <Tbody fontSize={'sm'}>
            {apiKeys.map(({ applyId, applyName, state, limit, weixinName, createTime, lastUseTime, containId }) => (
              <Tr key={applyId}>
                <Td>{applyName}</Td>
                <Td>{weixinName}</Td>
                {state == 1 ? (<Td color={'#008363'}>启用</Td>) : <Td>停用</Td>}

                {/* <Td>{usage}</Td> */}

                <Td whiteSpace={'pre-wrap'}>{dayjs(createTime).format('YYYY/MM/DD\nHH:mm:ss')}</Td>
                <Td whiteSpace={'pre-wrap'}>
                  {dayjs(lastUseTime).format('YYYY/MM/DD\nHH:mm:ss')}
                </Td>
                <Td>
                  <Menu autoSelect={false} isLazy>
                    <MenuButton
                      _hover={{ bg: 'myWhite.600  ' }}
                      cursor={'pointer'}
                      borderRadius={'md'}
                    >
                      <MyIcon name={'more'} w={'14px'} p={2} />
                    </MenuButton>
                    <MenuList color={'myGray.700'} minW={`120px !important`} zIndex={10}>
                      {/* <MenuItem
                        onClick={() =>
                          setEditData({
                            applyId,
                            name,
                            limit,
                            appId
                          })
                        }
                        py={[2, 3]}
                      >
                        <MyIcon name={'edit'} w={['14px', '16px']} />
                        <Box ml={[1, 2]}>{t('common.Edit')}</Box>
                      </MenuItem> */}
                      <MenuItem onClick={() => { onclickRemove(applyId, containId); stop(containId) }} py={[2, 3]}>
                        <MyIcon name={'delete'} w={['14px', '16px']} />
                        <Box ml={[1, 2]}>{t('common.Delete')}</Box>
                      </MenuItem>
                    </MenuList>
                  </Menu>
                </Td>
              </Tr>
            ))}
          </Tbody>
        </Table>
        <Loading loading={isGetting || isDeleting} fixed={false} />
      </TableContainer>
      {!!editData && (
        <EditKeyModal
          defaultData={editData}
          onClose={() => setEditData(undefined)}
          onCreate={(id) => {
            setApiKey(id);
            refetch();
            setEditData(undefined);
          }}
          onEdit={() => {
            refetch();
            setEditData(undefined);
          }}
        />
      )}
      <MyModal isOpen={!!apiKey} w={['400px', '600px']} onClose={() => setApiKey('')}>
        <Box py={3} px={5}>
          <Box fontWeight={'bold'} fontSize={'2xl'}>
            新的 API 秘钥
          </Box>
          <Box fontSize={'sm'} color={'myGray.600'}>
            请保管好你的秘钥，秘钥不会再次展示~
          </Box>
        </Box>
        <ModalBody>
          <Flex
            bg={'myGray.100'}
            px={3}
            py={2}
            whiteSpace={'pre-wrap'}
            wordBreak={'break-all'}
            cursor={'pointer'}
            onClick={() => copyData(apiKey)}
          >
            <Box flex={1}>{apiKey}</Box>
            <MyIcon ml={1} name={'copy'} w={'16px'}></MyIcon>
          </Flex>
        </ModalBody>
        <ModalFooter>
          <Button variant="base" onClick={() => setApiKey('')}>
            好的
          </Button>
        </ModalFooter>
      </MyModal>
    </Flex>
  );
};

export default React.memo(ApiKeyTable);

// console.log(appId);

// edit link modal
function EditKeyModal({
  defaultData,
  onClose,
  onCreate,
  onEdit
}: {
  defaultData: EditProps;
  onClose: () => void;
  onCreate: (id: string) => void;
  onEdit: () => void;
}) {
  const { t } = useTranslation();
  const isEdit = useMemo(() => !!defaultData._id, [defaultData]);
  // console.log(defaultData);


  const {
    register,
    setValue,
    handleSubmit: submitShareChat
  } = useForm({
    defaultValues: defaultData
  });
  // 获取容器
  const [imgId, setImg] = useState('')
  axios.get(`/apiss/getImageByAppId?appId=${defaultData.appId}`).then(res => {
    // console.log(3332,res.data.data);
    if (imgId == ''&&res.data.data!=null) {
      setImg(res.data.data.imageId)
    }

  })
  const [nowrongqi, setnowRongqi] = useState('')
  const [rongqi, setRongqi] = useState('')
  const [rongqis, setRongqis] = useState('')
  const selectAllContain = () => {
    // console.log('1221112312312321',defaultData.appId);

    axios.get(`/apiss/selectAllContainByImageId?imageId=${imgId}`).then(res => {
      console.log(22, res.data.data);
      // setRongqi(res.data.da)
      // console.log(res.data.data);
      var kong = res.data.data.filter(item => {
        return item.containState == 0
      })
      if (rongqis == '') {
        setRongqi(kong)
        setRongqis(res.data.data)
        console.log(rongqi, 1);

      }

    })
  }
  // selectAllContain()
  var [starting, setStartings] = useState(false);
  const [j, setJ] = useState(0)
  var [erwei, setErwei] = useState('');
  // var starting=false

  const { mutate: onclickCreate, isLoading: creating } = useRequest({
    mutationFn: async (e: EditProps) => createAOpenApiKey(e),
    errorToast: '创建链接异常',
    onSuccess: onCreate
  });
  const { mutate: onclickUpdate, isLoading: updating } = useRequest({
    mutationFn: (e: EditProps) => {
      //@ts-ignore
      return putOpenApiKey(e);
    },
    errorToast: '更新链接异常',
    onSuccess: onEdit
  });
  const [weixin, setWeixin] = useState('')
  // function juge() {
  //   // console.log(starting, '判断');

  //   axios.get('/apiss/selectInfo').then(juges => {
  //     // console.log(j);
  //     if (juges.data.data.length > 0) {
  //       // clearInterval(juge)
  //       setWeixin(juges.data.data[0]);

  //     }
  //     else if (juges.data.data.length == 0) {
  //       setTimeout(() => {
  //         console.log({starting});

  //         juge()
  //       }, 2500);
  //     }
  //   });
  // }
  //创建
  const create1 = (data) => {
    // console.log(weixin, 111);
    if (weixin != '') {
      axios.get(`/apiss/createApply?applyName=${data.name}&&containId=${nowrongqi}&&weixinId=${weixin.weixinId}`).then(res => {

        onCreate()
        axios.get('/apiss/delteWeixinInfo?weixinId=' + weixin.weixinId)
      })
    }
  };
  const update1 = (data) => {
    // console.log(weixin, 111);
    if (weixin != '') {
      axios.get(`/apiss/createApply?applyName=${data.name}&&containId=5&&weixinId=${weixin.weixinId}`).then(res => {
        onCreate()
      })
    }
  };
  const [inter, setInter] = useState([])
  useEffect(() => {

    // function juge() {
    //   axios.get('/apiss/selectInfo').then(juges => {
    //     console.log();
    //     if (juges.data.data.length > 0) {
    //       setWeixin(juges.data.data[0]);
    //     }
    //     else if (juges.data.data.length == 0 && starting == true) {
    //     }
    //   });
    // }

    // if (starting == true) {
    //   clearInterval(timer)
    //   console.log(timer);
    //   const timer = setInterval(() => {
    //     juge()
    //   }, 2500)
    //   // setInter(inter.push(timer))


    //   // console.log(timer,inter);

    // }

    // // 这里的函数会在count发生变化时触发
    // // console.log("Count has changed:",);
  }, [starting]);
  useEffect(() => {
    // console.log(3);
    var weixins = ''
    function juge() {
      axios.get('/apiss/selectInfo').then(juges => {
        console.log();
        if (juges.data.data.length > 0) {
          setWeixin(juges.data.data[0]);
          weixins = juges.data.data[0]
        }
        else if (juges.data.data.length == 0) {
        }
      });
    } const timer = setInterval(() => {
      juge()
    }, 2500)

    return () => {
      console.log(weixins, 1111);
      clearInterval(timer);


      if (weixins != '') {
        axios.get('/apiss/delteWeixinInfo?weixinId=' + weixins.weixinId)
      }

    };
  }, [])
  return (
    <MyModal
      w={'489px'}
      isOpen={true}
      title={isEdit ? t('outlink.Edit WEIXIN Key') : t('outlink.Create WEIXIN Key')}
    >
      <ModalBody>
        <Flex marginBottom={'20px'} alignItems={'center'}>
          <Box flex={'0 0 90px'}>{t('Name')}:</Box>
          <Input
            placeholder={t('微信名称') || 'key alias'}
            maxLength={20}
            {...register('name', {
              required: t('common.Name is empty') || 'Name is empty'
            })}
          />
        </Flex>
        <Flex alignItems={'center'} marginBottom={'20px'}>
          <Box flex={'0 0 90px'}>{t('状态')}:</Box>

          <Switch
            marginRight={'10px'}
            colorScheme="green"
            background={''}
            onChange={(e) => {

              // console.log(e.target.checked, 113);
              setStartings(e.target.checked);
              // setStartings(()=>{e.target.checked})
              // Promise.resolve().then(() => {
              //   setStartings([starting, e.target.checked]); // 此时赋值前 arr 为：[0]
              // })
              // console.log(starting);

              if (e.target.checked ) {
                // setStartings(true)
                setJ(1)
                // console.log(45551, j);

               let suiji= Math.random() * (100000 - 1) + 1;
                axios.get(`/apiss/createContainer?imageId=${imgId}&containName=${suiji}`).then((res) => {
                  console.log(res.data.data);
                  setnowRongqi(res.data.data)
                  setTimeout(() => {
                    axios.get('/apiss/findLastOne').then((datas) => {
                      console.log(datas.data.data);
                      setErwei(datas.data.data.codeTwo);
                      // juge()
                      // juge()
                      // console.log(e.target.checked, starting);
                    });
                  }, 1500);
                });
              } else  {
                // setStartings(false)
                setJ(0)
                axios.get(`/apiss/deleteContainer?containId=${nowrongqi}`).then((res) => {
                  // console.log(res);
                  setErwei('');
                });
              }
            }}
          />
          {starting ? <Box color={'#008363'}>已启用</Box> : <Box color={'#868686'}>已停用</Box>}
          { }
          {/* <Switch   thumb="green"  /> */}
        </Flex>
        {starting && weixin == '' ? (
          <Flex alignItems={'flex-start'}>
            <Box flex={'0 0 90px'}>{t('二维码')}:</Box>
            {erwei && weixin.length == 0 ? (
              <img src={erwei} width={'329px'} height={'329px'} alt="" />
            ) : (
              <Spinner
                thickness="4px"
                speed="0.65s"
                emptyColor="gray.200"
                color="blue.500"
                size="xl"
              />
            )}
            {/* <img src={erwei} width={'329px'} height={'329px'} alt="" /> */}
          </Flex>
        ) : (
          <Box></Box>
        )}
        {starting && weixin != '' ? (
          <Flex alignItems={'flex-start'}>
            <Box flex={'0 0 90px'}>{t('微信名')}:</Box>
            <Box flex={'0 0 90px'}>{weixin.weixinName}</Box>

          </Flex>


        ) : ''}


        {feConfigs?.isPlus && (
          <>
            <Flex alignItems={'center'} mt={4}>
              <Flex flex={'0 0 90px'} alignItems={'center'}>
                {t('common.Max credit')}:
                <MyTooltip label={t('common.Max credit tips' || '')}>
                  <QuestionOutlineIcon ml={1} />
                </MyTooltip>
              </Flex>
              <Input
                {...register('limit.credit', {
                  min: -1,
                  max: 1000,
                  valueAsNumber: true,
                  required: true
                })}
              />
            </Flex>

            <Flex alignItems={'center'} mt={4}>
              <Flex flex={'0 0 90px'} alignItems={'center'}>
                {t('common.Expired Time')}:
              </Flex>
              <Input
                type="datetime-local"
                defaultValue={
                  defaultData.limit?.expiredTime
                    ? dayjs(defaultData.limit?.expiredTime).format('YYYY-MM-DDTHH:mm')
                    : ''
                }
                onChange={(e) => {
                  setValue('limit.expiredTime', new Date(e.target.value));
                }}
              />
            </Flex>
          </>
        )}
      </ModalBody>

      <ModalFooter>
        <Button variant={'base'} mr={3} onClick={(data) => {
          onClose(); axios.get(`/apiss/deleteContainer?containId=${nowrongqi}`); 

        }}>
          {t('Cancel')}
        </Button>

        <Button
          background={'#008363'}
          isLoading={creating || updating}
          onClick={submitShareChat((data) => (isEdit ? update1(data) : create1(data)))}
        >
          {t('Confirm')}
        </Button>
      </ModalFooter>
    </MyModal>
  );
}
